package com.xiu.weixin.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;

public class XmlUtil {
	public static Map<String, String> parseRequrst(InputStream is) {
		SAXReader sax = new SAXReader();
		Map<String, String> map = new HashMap<String, String>();
		Document document;
		try {
			document = sax.read(is);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (Element element : elements) {
				map.put(element.getName(), element.getText());
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return map;
	}

	public static String beanToXml(Object object) {
		XStream xstream = new XStream();
		// xstream.processAnnotations(TextMessage.class);
		// xstream.processAnnotations(ImageMessage.class);
		// xstream.processAnnotations(MusicMessage.class);
		// xstream.processAnnotations(VoiceMessage.class);
		// xstream.processAnnotations(VideoMessage.class);
		// xstream.processAnnotations(NewsMessage.class);
		if (object.getClass().isAnnotationPresent(XStreamAlias.class)) {
			xstream.processAnnotations(object.getClass());
		}
		return xstream.toXML(object);
	}
}
